from peewee import DoesNotExist

from common.config.settings import Settings
from common.pkg.str_id import IdWorker, IdWorkerConfig


async def init_id_worker(settings: Settings):
    from common.g.g import G_MGW, G_LOGGER
    from common.model.config.id_worker_config import IdWorkerModel

    async with G_MGW.atomic() as f:
        try:
            q = IdWorkerModel.select().where(IdWorkerModel.in_use == False, IdWorkerModel.removed == False)
            c = await G_MGW.get(q)
            uq = await IdWorkerModel.update_instance(G_MGW, condition={"config_id": c.config_id},
                                                     update_fields={"in_use": True})
            if uq:
                id_config = IdWorkerConfig(**settings.id_worker_config.dict())
                return IdWorker(id_config, c.data_center_id, c.worker_id)
        except DoesNotExist:
            raise RuntimeError("机器耗光")
        except Exception as e:
            await f.rollback()
            G_LOGGER.exception(e)
            raise RuntimeError("异常")
        return None


async def close_id_worker(id_worker: IdWorker):
    from common.g.g import G_MGW, G_LOGGER
    from common.model.config.id_worker_config import IdWorkerModel
    try:
        await IdWorkerModel.update_instance(G_MGW, condition={"data_center_id": id_worker.datacenter_id,
                                                              "worker_id": id_worker.worker_id,
                                                              "in_use": True},
                                            update_fields={"in_use": False})
    except Exception as e:
        G_LOGGER.exception(f"还原数据中心配置异常:{e} data_center_id={id_worker.datacenter_id} worker_id={id_worker.worker_id}")